package com.lzt.admin.common.utils;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzt.admin.api.result.ResultAPI;
import com.lzt.admin.vo.UserDetailsVO;
import com.lzt.admin.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class PrintResponseUtil implements ResultAPI {
    private final ObjectMapper objectMapper;
    private void print(HttpServletResponse response, Map<String,Object> map) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = response.getWriter();
        String json = objectMapper.writeValueAsString(map);
        writer.write(json);
        response.flushBuffer();
    }
    public void printSuccess(HttpServletRequest request, HttpServletResponse response, UserDetailsVO user) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put(CODE_TAG,DEFAULT_HTTP_SUCCESS_CODE);
        map.put(MSG_TAG,DEFAULT_HTTP_SUCCESS_MSG);
        UserVO userVO = BeanUtil.copyProperties(user.getUserDTO(), UserVO.class);
        map.put("user",userVO);
        map.put("username", userVO.getUsername());
        map.put("uuid", userVO.getUuid());
        map.put("admin",user.getUserDTO().getAdmin().toString());
//        String orgName = user.getUser().getOrgName();
//        if(!Objects.isNull(orgName)){
//            map.put("orgName", orgName);
//        }
//        String token = jwt.createToken(map);
        print(response,map);
    }

    public void printFail(HttpServletRequest request, HttpServletResponse response, String msg) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put(CODE_TAG,DEFAULT_HTTP_ERROR_CODE);
        map.put(MSG_TAG,msg);
        print(response,map);
    }
}
